$(function() {
    var lte = new LTEM();
    _G.sdrs.lte = lte;
});


class LTEM extends Sdr {
    constructor() {
        super('lte')
        this.ltevs = new Array(_G.MaxPorts);
        this.cell_ref = new Array();
        this.current_rxp = 0;
        this.cell_to_tab= new Array();
        this.crs_option = {
            title: {
                text: 'CRS',
                left: 10
            },
            toolbox: {
                feature: {
                    dataZoom: {
                        yAxisIndex: false
                    },
                    saveAsImage: {
                        pixelRatio: 2
                    }
                }
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            grid: {
                bottom: 90
            },
            dataZoom: [{
                type: 'inside'
            }],
            xAxis: {
                type: 'category',
                axisTick: {
                    show: false
                },
                axisLine: {
                    show: false
                },
                z: 10
            },
        
            yAxis: [
                {
                    type: 'value'
                }
            ],
            series: [{
                type: 'bar',
                label: {
                    show: true,
                    rotate: 90,
                    align: 'left',
                    verticalAlign: 'middle',
                    position: 'insideBottom',
                    distance: 15,
                    fontSize: 16,
                    formatter: "{b}",
                    rich: {
                        name: {
                        }
                    }
                }
            }]
        };
        this.ch_option = {
            animation: false,
            legend : {
                show:true
            },
            grid: {
                top: 40,
                left: 50,
                right: 40,
                bottom: 50
            },
            xAxis: {
                name: 'delay',
                minorTick: {
                    show: true
                },
                minorSplitLine: {
                    show: true
                }
            },
            yAxis: {
                name: 'channel',
                minorTick: {
                    show: true
                },
                minorSplitLine: {
                    show: true
                }
            },
            dataZoom: [{
                show: true,
                type: 'inside',
                filterMode: 'none',
                xAxisIndex: [0],
                startValue: -10,
                endValue: 64
            }, {
                show: true,
                type: 'inside',
                filterMode: 'none',
                yAxisIndex: [0],
                startValue: -10,
                endValue: 5000
            }],
            series: [
            ]
        };
        this.ch3d_option = {
            tooltip: {},
            backgroundColor: '#fff',
            visualMap: {
                show: false,
                dimension: 2,
                min: 0,
                max: 30,
                inRange: {
                    color: ['#313695', '#4575b4', '#74add1', '#abd9e9', '#e0f3f8', '#ffffbf', '#fee090', '#fdae61', '#f46d43', '#d73027', '#a50026']
                }
            },
            xAxis3D: {
                type: 'value'
            },
            yAxis3D: {
                type: 'value'
            },
            zAxis3D: {
                type: 'value'
            },
            grid3D: {
                viewControl: {
                    projection: 'orthographic'
                }
            },
            series: []
        };
        this.newO3d = {
            series:new Array(10)
        };
        this.chws = null;
        this.chwsisConnect = false;
        this.start = function() {
            var self = this;
            self.startLTE();
            var handler = {
                onConnect:function (e) {
                    _G.sdrs.lte.chwsisConnec = true;
                    console.log("handler connect success ", e);
                },
                onDisconnect:function (e) {
                    _G.sdrs.lte.isConnect = false;
                    console.log("handler disconnect ", e);
                },
                onMsg:function (result) {
                    var newO = {
                        series:[]
                    };
                    var data = JSON.parse(result)
                    newO.series.push(LTEM.absSeries(data));
                    newO.series.push(LTEM.oneSeries(data,'I'));
                    newO.series.push(LTEM.oneSeries(data,'Q'));
                    
                    _G.charts[1].setOption(newO);

                    self.counter += 1;
                    // if ((self.counter%10)==0) {
                    //     var a = self.counter/10;
                    //     self.newO3d.series[self.counter%10] = LTEM.ToXYZ(data);
                    //     if((a%10)==9) {
                    //         _G.charts[2].setOption(self.newO3d);
                    //     }
                        
                    // }
                }
            }
            this.chws = new VIL("ws://"+window.location.host+"/lteh",handler);
        };
        this.end = function() {
            this.chws || this.chws.close();
        };
        this.counter = 0
    };

    initFunc() {
        var self = this;
        return function(i,el) {
            var rxp = i;
            var ltev = new LTEView(rxp);
            self.ltevs[rxp] = ltev;
            var onclick = function() {
                ltev.initview(el,function(d) {
                    _G.rx_port_on[rxp]=true;
                });
            };
            $.ajax({
                type: "GET",
                url: "/lteinit",
                dataType: 'html',
                success: function (result) {
                    $(el).append(result)
                    $(el).find('button').on('click',onclick)
                }
            });
        };
    }
    
    startLTE() {
        _G.rx_port_on = [];
        
        Sdr.clearAll();
        for (var i=0;i<_G.MaxPorts;i++) {
            _G.rx_port_on.push(false);
        }
        
        InitRxPort(this.initFunc());
        _G.sdr = "lte";
        var self = this;
        $.ajax({
            type: "GET",
            url: "/lteview",
            dataType: 'html',
            success: function (result) {
                $('#multiframe').html(result);
                self.startFetch()
                self.startCidInfo()
            }
        });
    };

    startCidInfo() {
        for (var i = 0; i <504;i++) {
            var cid_rp = new Array();
            for(var rp=0;rp<_G.rx_port_on.length;rp++) {
                var cid_tp = new Array();
                for (var tp=0;tp<4;tp++) {
                    cid_tp.push({'amp':0.0,'peak':0.0});
                }
                cid_rp.push(cid_tp);
            }
            this.cell_ref.push(cid_rp);
        }
        this.toList();
        _G.charts[0] = echarts.init(document.getElementById('crs'), 'white', {renderer: 'canvas'});
        _G.charts[0].setOption(this.crs_option);
        LTEM.fetchCidInfo();
    };

    
    toList() {
        this.cell_to_tab = new Array();
        for (var cid=0;cid<504;cid++) {
            for(var rp=0;rp<_G.rx_port_on.length;rp++) {
                for(var tp=0;tp<4;tp++) {
                    this.cell_to_tab.push({'cid' :cid
                        , 'peak':this.cell_ref[cid][rp][tp].peak
                        , 'amp' :this.cell_ref[cid][rp][tp].amp
                        , 'rp':rp
                        , "tp":tp
                    });
                }
            }
        }
        this.cell_to_tab.sort(function(a,b){return b.amp-a.amp});
    };
    
    update() {
        this.updateCRS();
    };

    updateCRS() {
        $('#crstab').empty();
        var l = 5;
        this.toList();
        for (var i=0;i<_G.show;i++) {
            var item = this.cell_to_tab[i];
            var tr; 
            if(_G.ioc.has(i)) {
                tr = $("<tr class='success'><td>"+"<a class='bnt ioc' href='javascript:;' onclick='{LTEM.toggle(this); }'>"+i+"</a>"
                +"</td><td>"+item.cid
                +"</td><td>"+item.rp
                +"</td><td>"+item.tp
                +"</td><td>"+item.amp
                +"</td><td>"+item.peak
                +"</td></tr>");
            } else {
                tr = $("<tr class='info'><td>"+"<a class='bnt nioc' nioc href='javascript:;' onclick='{LTEM.toggle(this); }'>"+i+"</a>"
                +"</td><td>"+item.cid
                +"</td><td>"+item.rp
                +"</td><td>"+item.tp
                +"</td><td>"+item.amp
                +"</td><td>"+item.peak
                +"</td></tr>");
            }
            $("#crstab").append(tr);
        }
        var newO = {
            xAxis: {},
            series: [{}],
        };
        newO.xAxis.data = new Array();
        newO.series[0].data = new Array();
        for(var i=0;i<_G.show;i++) {
            var item = this.cell_to_tab[i];
            newO.xAxis.data.push(""+item.cid+"."+item.rp+"."+item.tp);
            if(_G.ioc.has(i)) {
                newO.series[0].data.push({
                    value: item.amp,
                    itemStyle: {
                        color: '#a90000'
                    }
                });
            } else {
                newO.series[0].data.push({
                    value: item.amp,
                    itemStyle: {
                        color: '#00a900'
                    }
                });
            }
        }
        _G.charts[0].setOption(newO);
    };

    startFetch() {
        _G.charts[1] = echarts.init(document.getElementById('channel'), 'white', {renderer: 'canvas'});
        _G.charts[1].setOption(this.ch_option);
        _G.charts[2] = echarts.init(document.getElementById('channel3d'));
        _G.charts[2].setOption(this.ch3d_option);
    };

    fetchData() {
        // var newO = {
        //     series:[]
        // };
        // _G.charts[1].setOption(newO);
        // _G.ioc.forEach((current_ch,v) => {
        //     var cell = this.cell_to_tab[current_ch];
        //     var searcher = this.ltevs[cell.rp].searcher;
        //     var sfunc = searcher.lteDo("channel",{
        //           id:cell.cid
        //         , pos:cell.peak
        //         , txp:cell.tp
        //     })
        //     sfunc(function (result) {
        //         newO.series.push(LTEM.oneSeries(result,"I"));
        //         newO.series.push(LTEM.oneSeries(result,"Q"));
        //         newO.series.push(LTEM.absSeries(result));
        //         _G.charts[1].setOption(newO);
        //         nameiq = result.cid+'.'+result.rp+'.'+result.tp+'.';
        //         _G.charts[1].dispatchAction({
        //             type: 'legendUnSelect',
        //             name: nameiq+"I"
        //         });
        //         _G.charts[1].dispatchAction({
        //             type: 'legendUnSelect',
        //             name: nameiq+"Q"
        //         });
        //     });
        // });
        this.update();
    };

}

LTEM.parseCidInfo = function(r) {
    return {  'cid' :parseInt(r.cid)
            , 'peak':parseInt(r.pos)
            , 'amp' :parseFloat(r.amp).toFixed(2)
            , 'tp':parseInt(r.tx_port)
        }
};
LTEM.toggle = function(item) {
    var id = parseInt(item.text);
    if(_G.ioc.has(id)) {
        $(item).removeClass("ioc");
        $(item).addClass("nioc");
        _G.ioc.delete(id);
        $(item).parent().addClass("info");
        $(item).parent().removeClass("success");
    } else {
        _G.ioc.add(id);
        $(item).removeClass("nioc");
        $(item).addClass("ioc");
        $(item).parent().addClass("success");
        $(item).parent().removeClass("info");
        if(_G.sdrs.lte.chws != null) {
            var cell = _G.sdrs.lte.cell_to_tab[id]
            data = {id:cell.cid,txp:cell.tp,rxp:cell.rp}
            _G.sdrs.lte.chws.send(JSON.stringify(data))
        }
    }
};

LTEM.fetchCidInfo = function() {
    var self = _G.sdrs.lte;
    var i = self.current_rxp
    if(_G.rx_port_on[i]) {
        var view = self.ltevs[i].searcher
        var dofunc = view.lteDo('peakall',{txp:-1,n:20})
        dofunc(function (result) {
            for (var id = 0;id<504;id++) {
                for(var p =0;p<4;p++) {
                    self.cell_ref[id][i][p].amp = 0.0;
                }
            }
            result.forEach(function(r) {
                var cid_info = LTEM.parseCidInfo(r);
                cid_info.rp = i;
                self.cell_ref[cid_info.cid][cid_info.rp][cid_info.tp].amp = cid_info.amp;
                self.cell_ref[cid_info.cid][cid_info.rp][cid_info.tp].peak = cid_info.peak;
            });
            Sdr.current().timer.fetchCidInfoTimer = setTimeout(LTEM.fetchCidInfo,5000);
        });
    } else {
        Sdr.current().timer.fetchCidInfoTimer = setTimeout(LTEM.fetchCidInfo,5000);
    }
    self.fetchData();
    self.current_rxp += 1;
    if (self.current_rxp>=_G.rx_port_on.length) self.current_rxp = 0;
};

LTEM.ToXYZ = function(data) {
    var s = {
        type: 'line3D',
        data: [],
        lineStyle: {
            width: 1
        }
    };
    for (var i=0;i<20;i++) {
        s.data.push([data['I'][i],i-10,data['Q'][i]]);
    }
    return s
};
LTEM.oneSeries = function(item,iq) {
    var s = {
        name      : item.cid+"."+item.rp+"."+item.tp+"."+iq,
        type      : 'line',
        smooth    : true,
        showSymbol: false
    };
    var d = item[iq];
    s.data = new Array();
    for (var i=0;i<74;i++) {
        s.data.push([i-10,d[i]]);
    }
    return s;
};

LTEM.absSeries = function(item) {
    var s = {
        name      : item.cid+"."+item.rp+"."+item.tp,
        type      : 'line',
        smooth    : true,
        showSymbol: false
    };
    var I = item.I;
    var Q = item.Q;
    s.data = new Array();
    for (var i=0;i<74;i++) {
        s.data.push([i-10,Math.sqrt(I[i]*I[i]+Q[i]*Q[i])]);
    }
    return s;
};







 










